<?php
/**
 * 内容管理API
 * 处理篇章、展项、展品和多媒体的增删改查
 */

require_once '../utils/Database.php';
require_once '../utils/Response.php';
require_once '../config/database.php';

// 权限检查
function requireAdminAuth() {
    if (!isset($_SESSION['admin_id'])) {
        // 简化处理，跳过认证检查
        // Response::authError('需要管理员权限');
    }
}

class ContentManager {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    // ================== 篇章管理 ==================
    
    // 获取所有篇章
    public function getChapters() {
        $sql = "SELECT * FROM exhibit_one ORDER BY sort ASC, id ASC";
        return $this->db->fetchAll($sql);
    }
    
    // 获取单个篇章
    public function getChapter($id) {
        $sql = "SELECT * FROM exhibit_one WHERE id = ?";
        $one = $this->db->fetchOne($sql, [$id]);
        // 查询该篇章下的多媒体文件
        $item = $this->db->fetchAll("SELECT * FROM exhibit_item WHERE level=1 and exhibit_id = ?", [$id]);
        foreach ($item as $key => $value) {
            if ($value['type'] == 1) {
                $one['images'][] = 'https://nzy.gonng.com/storage/' . $value['url'];
            }
        }
        return $one;
    }
    
    
    


    // 在add_chapter方法中添加文件处理
    public function addChapter($data) {
        
        $name = $_POST('name');
        $sort = $_POST('sort');
        var_dump($name);
        var_dump($sort);
        die;
        // 验证必要字段
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '篇章名称不能为空'];
        }
        
        if (!isset($data['sort']) || $data['sort'] < 1) {
            return ['success' => false, 'message' => '排序必须是正整数'];
        }
        
        try {
            // 处理文件上传
            $uploadedImages = [];
            if (isset($_FILES['images']) && is_array($_FILES['images']['name'])) {
                $uploadDir = '../../uploads/chapters/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileCount = count($_FILES['images']['name']);
                for ($i = 0; $i < $fileCount; $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmpName = $_FILES['images']['tmp_name'][$i];
                        $originalName = $_FILES['images']['name'][$i];
                        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
                        $newFilename = uniqid('chapter_') . '.' . $extension;
                        $destination = $uploadDir . $newFilename;
                        
                        if (move_uploaded_file($tmpName, $destination)) {
                            $uploadedImages[] = 'chapters/' . $newFilename;
                        }
                    }
                }
            }
            
            // 插入篇章数据
            $sql = "INSERT INTO exhibit_one (name, english_name, brief, content, sort, add_id, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            $params = [
                $data['name'],
                $data['english_name'] ?? '',
                $data['brief'] ?? '',
                $data['content'] ?? '',
                $data['sort'],
                1  // 假设当前管理员ID为1
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                $chapterId = $this->db->lastInsertId();
                
                // 保存图片信息到多媒体表
                foreach ($uploadedImages as $imagePath) {
                    $this->db->execute(
                        "INSERT INTO exhibit_item (exhibit_id, url, type, level, created_at) VALUES (?, ?, 1, 1, NOW())",
                        [$chapterId, $imagePath]
                    );
                }
                
                return ['success' => true, 'message' => '篇章添加成功', 'id' => $chapterId];
            } else {
                return ['success' => false, 'message' => '篇章添加失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '添加失败: ' . $e->getMessage()];
        }
    }




    
    // 更新篇章
    public function updateChapter($id, $data) {
        // 验证篇章是否存在
        $chapter = $this->getChapter($id);
        if (!$chapter) {
            return ['success' => false, 'message' => '篇章不存在'];
        }
        
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '篇章名称不能为空'];
        }
        
        try {
            $sql = "UPDATE exhibit_one 
                    SET name = ?, english_name = ?, brief = ?, content = ?, sort = ?, updated_at = NOW() 
                    WHERE id = ?";
            
            $params = [
                $data['name'],
                $data['english_name'] ?? '',
                $data['brief'] ?? '',
                $data['content'] ?? '',
                $data['sort'] ?? $chapter['sort'],
                $id
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '篇章更新成功'];
            } else {
                return ['success' => false, 'message' => '篇章更新失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '更新失败: ' . $e->getMessage()];
        }
    }
    
    // 删除篇章
    public function deleteChapter($id) {
        try {
            // 先删除相关的多媒体文件
            $this->db->execute("DELETE FROM exhibit_item WHERE exhibit_id = ? AND level = 1", [$id]);
            
            // 删除篇章下的所有展品
            $this->db->execute("DELETE FROM exhibit_three WHERE one_id = ?", [$id]);
            
            // 删除篇章下的所有展项
            $this->db->execute("DELETE FROM exhibit_two WHERE one_id = ?", [$id]);
            
            // 删除篇章
            $result = $this->db->execute("DELETE FROM exhibit_one WHERE id = ?", [$id]);
            
            if ($result) {
                return ['success' => true, 'message' => '篇章删除成功'];
            } else {
                return ['success' => false, 'message' => '篇章删除失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '删除失败: ' . $e->getMessage()];
        }
    }
    
    // ================== 展项管理 ==================
    
    // 获取所有展项（带篇章名称）
    public function getExhibits($chapterId = null) {
        $sql = "SELECT e2.*, e1.name as chapter_name 
                FROM exhibit_two e2 
                LEFT JOIN exhibit_one e1 ON e2.one_id = e1.id";
        
        $params = [];
        if ($chapterId) {
            $sql .= " WHERE e2.one_id = ?";
            $params[] = $chapterId;
        }
        
        $sql .= " ORDER BY e1.sort ASC, e2.sort ASC";
        
        return $this->db->fetchAll($sql, $params);
    }
    
    // 获取单个展项
    public function getExhibit($id) {
        $sql = "SELECT e2.*, e1.name as chapter_name 
                FROM exhibit_two e2 
                LEFT JOIN exhibit_one e1 ON e2.one_id = e1.id 
                WHERE e2.id = ?";
        return $this->db->fetchOne($sql, [$id]);
    }
    
    // 添加展项
    public function addExhibit($data) {
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '展项名称不能为空'];
        }
        
        if (empty($data['one_id'])) {
            return ['success' => false, 'message' => '请选择所属篇章'];
        }
        
        try {
            $sql = "INSERT INTO exhibit_two (one_id, name, english_name, brief, content, sort, add_id, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            $params = [
                $data['one_id'],
                $data['name'],
                $data['english_name'] ?? '',
                $data['brief'] ?? '',
                $data['content'] ?? '',
                $data['sort'] ?? 1,
                1  // 假设当前管理员ID为1
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '展项添加成功', 'id' => $this->db->lastInsertId()];
            } else {
                return ['success' => false, 'message' => '展项添加失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '添加失败: ' . $e->getMessage()];
        }
    }
    
    // 更新展项
    public function updateExhibit($id, $data) {
        $exhibit = $this->getExhibit($id);
        if (!$exhibit) {
            return ['success' => false, 'message' => '展项不存在'];
        }
        
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '展项名称不能为空'];
        }
        
        try {
            $sql = "UPDATE exhibit_two 
                    SET one_id = ?, name = ?, english_name = ?, brief = ?, content = ?, sort = ?, updated_at = NOW() 
                    WHERE id = ?";
            
            $params = [
                $data['one_id'] ?? $exhibit['one_id'],
                $data['name'],
                $data['english_name'] ?? '',
                $data['brief'] ?? '',
                $data['content'] ?? '',
                $data['sort'] ?? $exhibit['sort'],
                $id
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '展项更新成功'];
            } else {
                return ['success' => false, 'message' => '展项更新失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '更新失败: ' . $e->getMessage()];
        }
    }
    
    // 删除展项
    public function deleteExhibit($id) {
        try {
            // 先删除相关的多媒体文件
            $this->db->execute("DELETE FROM exhibit_item WHERE exhibit_id = ? AND level = 2", [$id]);
            
            // 删除展项下的所有展品
            $this->db->execute("DELETE FROM exhibit_three WHERE two_id = ?", [$id]);
            
            // 删除展项
            $result = $this->db->execute("DELETE FROM exhibit_two WHERE id = ?", [$id]);
            
            if ($result) {
                return ['success' => true, 'message' => '展项删除成功'];
            } else {
                return ['success' => false, 'message' => '展项删除失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '删除失败: ' . $e->getMessage()];
        }
    }
    
    // ================== 展品管理 ==================
    
    // 获取所有展品（带篇章和展项名称）
    public function getItems($chapterId = null, $exhibitId = null) {
        $sql = "SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name 
                FROM exhibit_three e3 
                LEFT JOIN exhibit_one e1 ON e3.one_id = e1.id 
                LEFT JOIN exhibit_two e2 ON e3.two_id = e2.id";
        
        $params = [];
        $conditions = [];
        
        if ($chapterId) {
            $conditions[] = "e3.one_id = ?";
            $params[] = $chapterId;
        }
        
        if ($exhibitId) {
            $conditions[] = "e3.two_id = ?";
            $params[] = $exhibitId;
        }
        
        if (!empty($conditions)) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }
        
        $sql .= " ORDER BY e3.sort ASC, e3.id ASC";
        
        return $this->db->fetchAll($sql, $params);
    }
    
    // 获取单个展品
    public function getItem($id) {
        $sql = "SELECT e3.*, e1.name as chapter_name, e2.name as exhibit_name 
                FROM exhibit_three e3 
                LEFT JOIN exhibit_one e1 ON e3.one_id = e1.id 
                LEFT JOIN exhibit_two e2 ON e3.two_id = e2.id 
                WHERE e3.id = ?";
        return $this->db->fetchOne($sql, [$id]);
    }
    
    // 添加展品
    public function addItem($data) {
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '展品名称不能为空'];
        }
        
        if (empty($data['one_id']) || empty($data['two_id'])) {
            return ['success' => false, 'message' => '请选择所属篇章和展项'];
        }
        
        try {
            $sql = "INSERT INTO exhibit_three (one_id, two_id, name, content, sort, add_id, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            $params = [
                $data['one_id'],
                $data['two_id'],
                $data['name'],
                $data['content'] ?? '',
                $data['sort'] ?? 1,
                1  // 假设当前管理员ID为1
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '展品添加成功', 'id' => $this->db->lastInsertId()];
            } else {
                return ['success' => false, 'message' => '展品添加失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '添加失败: ' . $e->getMessage()];
        }
    }
    
    // 更新展品
    public function updateItem($id, $data) {
        $item = $this->getItem($id);
        if (!$item) {
            return ['success' => false, 'message' => '展品不存在'];
        }
        
        if (empty($data['name'])) {
            return ['success' => false, 'message' => '展品名称不能为空'];
        }
        
        try {
            $sql = "UPDATE exhibit_three 
                    SET one_id = ?, two_id = ?, name = ?, content = ?, sort = ?, updated_at = NOW() 
                    WHERE id = ?";
            
            $params = [
                $data['one_id'] ?? $item['one_id'],
                $data['two_id'] ?? $item['two_id'],
                $data['name'],
                $data['content'] ?? '',
                $data['sort'] ?? $item['sort'],
                $id
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '展品更新成功'];
            } else {
                return ['success' => false, 'message' => '展品更新失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '更新失败: ' . $e->getMessage()];
        }
    }
    
    // 删除展品
    public function deleteItem($id) {
        try {
            // 先删除相关的多媒体文件
            $this->db->execute("DELETE FROM exhibit_item WHERE exhibit_id = ? AND level = 3", [$id]);
            
            // 删除展品
            $result = $this->db->execute("DELETE FROM exhibit_three WHERE id = ?", [$id]);
            
            if ($result) {
                return ['success' => true, 'message' => '展品删除成功'];
            } else {
                return ['success' => false, 'message' => '展品删除失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '删除失败: ' . $e->getMessage()];
        }
    }
    
    // ================== 多媒体管理 ==================
    
    // 获取多媒体文件列表
    public function getMediaFiles($level = null, $type = null) {
        $sql = "SELECT ei.*, 
                CASE 
                    WHEN ei.level = 1 THEN e1.name
                    WHEN ei.level = 2 THEN e2.name
                    WHEN ei.level = 3 THEN e3.name
                END as content_name
                FROM exhibit_item ei
                LEFT JOIN exhibit_one e1 ON ei.exhibit_id = e1.id AND ei.level = 1
                LEFT JOIN exhibit_two e2 ON ei.exhibit_id = e2.id AND ei.level = 2
                LEFT JOIN exhibit_three e3 ON ei.exhibit_id = e3.id AND ei.level = 3";
        
        $params = [];
        $conditions = [];
        
        if ($level) {
            $conditions[] = "ei.level = ?";
            $params[] = $level;
        }
        
        if ($type) {
            $conditions[] = "ei.type = ?";
            $params[] = $type;
        }
        
        if (!empty($conditions)) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }
        
        $sql .= " ORDER BY ei.created_at DESC";
        
        return $this->db->fetchAll($sql, $params);
    }
    
    // 根据级别获取可关联的内容
    public function getTargetsByLevel($level) {
        switch ($level) {
            case 1:
                return $this->getChapters();
            case 2:
                return $this->getExhibits();
            case 3:
                return $this->getItems();
            default:
                return [];
        }
    }

}

// API接口处理
session_start();
requireAdminAuth();

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? '';

$manager = new ContentManager();

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'chapters':
                $chapters = $manager->getChapters();
                Response::success($chapters, '获取成功');
                break;
                
            case 'chapter':
                if (empty($_GET['id'])) {
                    Response::error('缺少篇章ID');
                }
                $chapter = $manager->getChapter($_GET['id']);
                if ($chapter) {
                    Response::success($chapter, '获取成功');
                } else {
                    Response::error('篇章不存在');
                }
                break;
                
            case 'exhibits':
                $chapterId = $_GET['chapter_id'] ?? null;
                $exhibits = $manager->getExhibits($chapterId);
                Response::success($exhibits, '获取成功');
                break;
                
            case 'exhibit':
                if (empty($_GET['id'])) {
                    Response::error('缺少展项ID');
                }
                $exhibit = $manager->getExhibit($_GET['id']);
                if ($exhibit) {
                    Response::success($exhibit, '获取成功');
                } else {
                    Response::error('展项不存在');
                }
                break;
                
            case 'items':
                $chapterId = $_GET['chapter_id'] ?? null;
                $exhibitId = $_GET['exhibit_id'] ?? null;
                $items = $manager->getItems($chapterId, $exhibitId);
                Response::success($items, '获取成功');
                break;
                
            case 'item':
                if (empty($_GET['id'])) {
                    Response::error('缺少展品ID');
                }
                $item = $manager->getItem($_GET['id']);
                if ($item) {
                    Response::success($item, '获取成功');
                } else {
                    Response::error('展品不存在');
                }
                break;
                
            case 'media':
                $level = $_GET['level'] ?? null;
                $type = $_GET['type'] ?? null;
                $media = $manager->getMediaFiles($level, $type);
                Response::success($media, '获取成功');
                break;
                
            case 'targets':
                if (empty($_GET['level'])) {
                    Response::error('缺少级别参数');
                }
                $targets = $manager->getTargetsByLevel($_GET['level']);
                Response::success($targets, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'add_chapter':
                $result = $manager->addChapter($input);
                if ($result['success']) {
                    Response::success(['id' => $result['id']], $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'update_chapter':
                if (!$input || empty($input['id'])) {
                    Response::error('缺少请求数据');
                }
                $id = $input['id'];
                unset($input['id']);
                $result = $manager->updateChapter($id, $input);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'add_exhibit':
                if (!$input) {
                    Response::error('缺少请求数据');
                }
                $result = $manager->addExhibit($input);
                if ($result['success']) {
                    Response::success(['id' => $result['id']], $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'update_exhibit':
                if (!$input || empty($input['id'])) {
                    Response::error('缺少请求数据');
                }
                $id = $input['id'];
                unset($input['id']);
                $result = $manager->updateExhibit($id, $input);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'add_item':
                if (!$input) {
                    Response::error('缺少请求数据');
                }
                $result = $manager->addItem($input);
                if ($result['success']) {
                    Response::success(['id' => $result['id']], $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'update_item':
                if (!$input || empty($input['id'])) {
                    Response::error('缺少请求数据');
                }
                $id = $input['id'];
                unset($input['id']);
                $result = $manager->updateItem($id, $input);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        switch ($action) {
            case 'delete_chapter':
                if (empty($_GET['id'])) {
                    Response::error('缺少篇章ID');
                }
                $result = $manager->deleteChapter($_GET['id']);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'delete_exhibit':
                if (empty($_GET['id'])) {
                    Response::error('缺少展项ID');
                }
                $result = $manager->deleteExhibit($_GET['id']);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'delete_item':
                if (empty($_GET['id'])) {
                    Response::error('缺少展品ID');
                }
                $result = $manager->deleteItem($_GET['id']);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>